package com.yourenbang.lingyun.transaction.web.controller.manage;

import com.alibaba.fastjson.JSONObject;
import com.yourenbang.lingyun.constants.BizCodeMessages;
import com.yourenbang.lingyun.constants.Constant;
import com.yourenbang.lingyun.constants.enums.FundBillType;
import com.yourenbang.lingyun.constants.enums.PlatNoEnums;
import com.yourenbang.lingyun.constants.enums.fund.AccountMainJournalType;
import com.yourenbang.lingyun.constants.enums.fund.AccountType;
import com.yourenbang.lingyun.core.base.controller.BaseController;
import com.yourenbang.lingyun.core.base.interceptor.ExcludeInterceptor;
import com.yourenbang.lingyun.core.message.Result;
import com.yourenbang.lingyun.core.model.vo.PageVO;
import com.yourenbang.lingyun.core.util.KLog;
import com.yourenbang.lingyun.core.util.http.HttpClientUtil;
import com.yourenbang.lingyun.domain.UserBase;
import com.yourenbang.lingyun.domain.UserBaseExample;
import com.yourenbang.lingyun.mapper.UserBaseMapper;
import com.yourenbang.lingyun.transaction.mapper.TransactionUserMapper;
import com.yourenbang.lingyun.transaction.web.domain.dto.fund.ManageChangeFundDTO;
import com.yourenbang.lingyun.transaction.web.domain.dto.fund.ManageFundTypeListDTO;
import com.yourenbang.lingyun.transaction.web.domain.dto.manage.*;
import com.yourenbang.lingyun.transaction.web.domain.vo.manage.ManageActivateRewardVO;
import com.yourenbang.lingyun.transaction.web.service.CommonService;
import com.yourenbang.lingyun.transaction.web.service.manage.ManageFundService;
import com.yourenbang.lingyun.transaction.web.service.manage.ManageService;
import com.yourenbang.lingyun.transaction.web.service.pay.TradeService;
import com.yourenbang.transaction.api.model.dto.fund.FundDetailDTO;
import com.yourenbang.transaction.api.model.dto.manage.ExportPledgeListDTO;
import com.yourenbang.transaction.api.model.dto.manage.QueryFundAccountDTO;
import com.yourenbang.transaction.api.model.dto.manage.TopupSysAccountDTO;
import com.yourenbang.transaction.api.model.vo.manage.QueryAccountTypeVO;
import com.yourenbang.transaction.api.model.vo.manage.QueryFundAccountDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Description
 * @Date 2020/10/30 10:02
 * @Created by Jason
 */

@Slf4j
@RestController
@RequestMapping("/transaction/manage")
public class ManageFundAccountController extends BaseController {
    @Autowired
    CommonService commonService;
    @Autowired
    private ManageService manageService;

    @Autowired
    private ManageFundService manageFundService;
    @Autowired
    private TransactionUserMapper transactionUserMapper;
    @Autowired
    private UserBaseMapper userBaseMapper;
    @Autowired
    private TradeService tradeService;

    /**
     * 系统账户充值
     *
     * @param dtoRequest
     * @param br
     * @return
     */
    @ExcludeInterceptor
    @PostMapping(value = "/topup/sys/account")
    public Result topupApply(@Validated @RequestBody TopupSysAccountDTO dtoRequest, BindingResult br) {
        Result result = verifyParam(br);
        if (!result.isSuccess()) {
            return result;
        }
        KLog.info("[系统账户充值入参]:{}", dtoRequest);

        return manageService.topupSysAccount(dtoRequest);
    }

    /**
     * 查询资金账户
     * <a href = "https://huoyan.kaolakuaishou.cn/project/97/interface/api/2190">接口链接</a>
     *
     * @return
     */
    @ExcludeInterceptor
    @GetMapping("/list/account")
    public Result<PageVO> getFundAccount(QueryFundAccountDTO dto) {
        if (dto.getPlatNo() == 0) {
            dto.setPlatNo(PlatNoEnums.KLKS.getCode().intValue());
        }
        KLog.info("[查询资金账户入参]:{}", dto);
        return manageService.getFundAccount((dto));
    }

    /**
     * 资金账户导出
     */
    @ExcludeInterceptor
    @GetMapping("/list/account/export")
    public void exportSystemAccount(QueryFundAccountDTO dto){
        KLog.info("导出资金账户入参:{}",dto);
        manageService.exportSystemAccount(dto);
    }

    /**
     * 查询资金账户详情
     * <a href = "https://huoyan.kaolakuaishou.cn/project/97/interface/api/2194">接口链接</a>
     *
     * @return
     */
    @ExcludeInterceptor
    @PostMapping("/detail/sys/account")
    public Result<QueryFundAccountDetailVO> getFundAccountDetail(@RequestBody FundDetailDTO fundDetailDTO) {
        KLog.info("查询资金账户详情入参:{}", fundDetailDTO);
        return manageService.getFundAccountDetail(fundDetailDTO);
    }

    /**
     * 查询资金账户详情和流水
     * <p>https://huoyan.kaolakuaishou.cn/project/97/interface/api/2194</p>
     *
     * @return
     */
    @ExcludeInterceptor
    @PostMapping("/detail/journal/sys/account")
    public Result<QueryFundAccountDetailVO> getFundAccountDetailAndJournal(@RequestBody FundDetailDTO fundDetailDTO) {
        KLog.info("查询资金账户详情流水入参:{}", fundDetailDTO);
        return manageService.getFundAccountDetailAndJournal(fundDetailDTO);
    }

    /**
     * 查询系统资金账户类型
     *
     * @return
     */
    @ExcludeInterceptor
    @GetMapping("/get/sys/account/type")
    public Result<List<QueryAccountTypeVO>> getFundAccountType(Short platNo) {
        return manageService.getFundAccountType(platNo);
    }

    /**
     * 查询后台账户账单明细
     * <a href="https://huoyan.kaolakuaishou.cn/project/97/interface/api/5806">火眼链接</a>
     *
     * @return
     */
    @ExcludeInterceptor
    @PostMapping("/fund/bill")
    public Result<PageVO> getFundBill(@RequestBody ManageFundBillDTO dto) {
        KLog.info("[管理后台]查询账单明细入参:{}", dto.toString());
        Result<PageVO> pageVOResult = manageFundService.queryFundBill(dto);
        KLog.info("[管理后台]查询账单明细入参:{},返回:{}", dto.toString(), pageVOResult.toString());
        return pageVOResult;
    }

    /**
     * 查询后台账户账单明细-津贴
     * <a href="https://huoyan.kaolakuaishou.cn/project/97/interface/api/13983">火眼链接</a>
     *
     * @return
     */
    @ExcludeInterceptor
    @PostMapping("/fund/bill/allowance")
    public Result<PageVO> getFundBillAllowance(@RequestBody ManageFundBillDTO dto) {
        KLog.info("[管理后台]查询津贴账单明细入参:{}", dto.toString());
        Result<PageVO> pageVOResult = manageFundService.queryFundBillAllowance(dto);
        KLog.info("[管理后台]查询津贴账单明细入参:{},返回:{}", dto.toString(), pageVOResult.toString());
        return pageVOResult;
    }

    /**
     * 查询后台用户账户列表
     *
     * @return
     * @see <a href="https://huoyan.kaolakuaishou.cn/project/97/interface/api/6030">火眼地址</a>
     */
    @ExcludeInterceptor
    @PostMapping("/user/account/list")
    public Result<PageVO> getUserAccountList(@RequestBody ManageUserAccountDTO dto) {
        KLog.info("[管理后台]查询后台用户账户列表入参:{}", dto.toString());

        String a9UserBaseId = getHttpServletRequest().getHeader(Constant.MANAGE_A9_UID_HEADER_NAME);
        if (StringUtils.isNotBlank(a9UserBaseId)) {
            dto.setA9UserBaseId(a9UserBaseId);
        }

        Result<PageVO> pageVOResult = manageFundService.queryUserAccountList(dto);
        KLog.info("[管理后台]查询后台用户账户列表入参:{},返回:{}", dto.toString(), pageVOResult.toString());
        return pageVOResult;
    }

    /**
     * 导出账号列表
     */
    @ExcludeInterceptor
    @GetMapping("/user/account/export")
    public void exportUserAccount(ManageUserAccountExportDTO dto){
        KLog.info("导出账号列表入参:{}",dto);
        manageFundService.exportUserAccount(dto);
    }

    /**
     * 查询后台返现关系
     *
     * @return
     * @see <a href="https://huoyan.kaolakuaishou.cn/project/97/interface/api/6038">火眼接口连接</a>
     */
    @ExcludeInterceptor
    @PostMapping("/activate/reward/list")
    public Result<PageVO<ManageActivateRewardVO>> getActivateRewardList(@RequestBody ManageAllyActivateRewardDTO dto) {

        KLog.info("[管理后台]查询返现关系入参:{}", dto.toString());

        String a9UserBaseId = getHttpServletRequest().getHeader(Constant.MANAGE_A9_UID_HEADER_NAME);
        if (StringUtils.isNotBlank(a9UserBaseId)) {
            dto.setA9UserBaseId(a9UserBaseId);
        }

        return manageFundService.queryRewardList(dto);
    }

    /**
     * 激活返现重置
     *
     * @see <a href="https://huoyan.kaolakuaishou.cn/project/97/interface/api/13458">火眼接口连接</a>
     */
    @ExcludeInterceptor
    @PostMapping("/activate/reward/reset")
    public Result resetActivateReward(@Validated @RequestBody ManageResetActivateRewardDTO dto, BindingResult br) {

        KLog.info("[管理后台]重置激活返现入参:{}", dto.toString());

        Result result = verifyParam(br);
        if (!result.isSuccess()) {
            return result;
        }

        return manageFundService.resetActivateReward(dto);
    }

    /**
     * 激活返现作废
     *
     * @see <a href="https://huoyan.kaolakuaishou.cn/project/97/interface/api/13464">火眼接口连接</a>
     */
    @ExcludeInterceptor
    @PostMapping("/activate/reward/invalid")
    public Result invalidActivateReward(@Validated @RequestBody ManageResetActivateRewardDTO dto, BindingResult br) {

        KLog.info("[管理后台]作废激活返现入参:{}", dto.toString());

        Result result = verifyParam(br);
        if (!result.isSuccess()) {
            return result;
        }

        return manageFundService.invalidActivateReward(dto);
    }

    @ExcludeInterceptor
    @PostMapping("/activate/reward/del")
    public Result delActivateReward(@Validated @RequestBody ManageResetActivateRewardDTO dto, BindingResult br) {

        KLog.info("[管理后台]删除激活返现关系入参:{}", dto.toString());

        Result result = verifyParam(br);
        if (!result.isSuccess()) {
            return result;
        }

        return manageFundService.delActivateReward(dto);
    }

    /**
     * 管理后台用户账户调整账户金额
     *
     * @see <a href="https://huoyan.kaolakuaishou.cn/project/799/interface/api/15276">火眼地址</a>
     */
    @ExcludeInterceptor
    @PostMapping("/account/changefund")
    public Result manageChangeFund(@Validated @RequestBody ManageChangeFundDTO dto, BindingResult br) {

        KLog.info("[管理后台]用户账户更改入参:{}", dto.toString());
        Result result = verifyParam(br);
        if (!result.isSuccess()) {
            return result;
        }


        UserBaseExample userBaseExample = new UserBaseExample();
        userBaseExample.createCriteria().andPlatNoEqualTo(dto.getPlatNo()).andPhoneEqualTo(dto.getUserPhone());
        List<UserBase> userBases = userBaseMapper.selectByExample(userBaseExample);
        if (CollectionUtils.isEmpty(userBases)) {
            return Result.builder().fail(BizCodeMessages.PARAMETER_ERR, "用户不存在");
        }

        if (PlatNoEnums.YXY.isEquals(dto.getPlatNo())) {

            Integer merAccount = AccountType.getFullCode(AccountType.MER, PlatNoEnums.YXY.getCode());
            Integer allyAllAccount = AccountType.getFullCode(AccountType.ALLY_V2, PlatNoEnums.YXY.getCode());
            Integer merAccountFromBoss = AccountType.getFullCode(AccountType.MERCHANT_FROM_BOSS, PlatNoEnums.YXY.getCode());
            Integer allyAllAccountFromBoss = AccountType.getFullCode(AccountType.ALLY_FROM_BOSS, PlatNoEnums.YXY.getCode());

            // 限制可调整账户
            if (!Arrays.asList(merAccount, allyAllAccount, merAccountFromBoss, allyAllAccountFromBoss).contains(dto.getAccountType())) {
                return Result.builder().fail(BizCodeMessages.PARAMETER_ERR);
            }


            if (ManageChangeFundDTO.ADD_AMOUNT.equals(dto.getChangeFundFlag()) || ManageChangeFundDTO.REVERSAL_AMOUNT.equals(dto.getChangeFundFlag())) {
                if (Objects.isNull(dto.getAccountMainJournalType())) {
                    return Result.builder().fail(BizCodeMessages.PARAMETER_ERR, "资金类型不能为空");
                }
            } else {
                //转换为对应的账户 进行后续的操作
                dto.setAccountMainJournalType(AccountMainJournalType.getSubtractMainJournalTypeByAccountType(dto.getAccountType()).getCode());
            }

        }

        if (ManageChangeFundDTO.ADD_AMOUNT.equals(dto.getChangeFundFlag())) {

            dto.setBillType(FundBillType.TYPE_450.getType());
            result = manageFundService.manageAddFund(dto);

        } else if (ManageChangeFundDTO.SUBTRACT_AMOUNT.equals(dto.getChangeFundFlag())) {

            // 提现账户减帐
            dto.setBillType(FundBillType.TYPE_451.getType());
            result = manageFundService.manageSubtractFund(dto);

        } else if (ManageChangeFundDTO.REVERSAL_AMOUNT.equals(dto.getChangeFundFlag())) {

            // 加帐冲正
            dto.setBillType(FundBillType.TYPE_452.getType());
            result = manageFundService.manageReversalFund(dto);

        } else {
            // 冻结
            String httpPostRequest = "";
            String postUrl = "https://testapi.mugeyrb.com/account/money/free";
            if (commonService.isProd()) {
                postUrl = "http://172.17.187.6:8886/account/money/free";
            }
            HashMap params = new HashMap();
            params.put("userPhone", dto.getUserPhone());
            params.put("accountType", dto.getAccountType());
            params.put("changeAmount", dto.getChangeAmount());
            params.put("detail", dto.getDetail());
            params.put("operator", dto.getOperator());
            params.put("platNo", 21);
            params.put("operatorType", 1);
            if (ManageChangeFundDTO.UNFREE_AMOUNT.equals(dto.getChangeFundFlag())) {
                params.put("operatorType", 2);
            }
            try {
                httpPostRequest = HttpClientUtil.httpPostRequest(postUrl, JSONObject.toJSONString(params));
            } catch (Exception e) {
                e.printStackTrace();
            }
            //Result result = allowanceManageService.myAwardBonusQuery(dto.getData());
            log.info("查询返回盟友通讯录,出参：{}", httpPostRequest);
            HashMap map = new HashMap();
            try {
                map = JSONObject.parseObject(httpPostRequest, HashMap.class);
            }catch (Exception e) {
                e.printStackTrace();
            }
            return Result.builder().success(map);
        }

        KLog.info("[管理后台]用户账户更改入参:{},返回:{}", dto.toString(), result.toString());
        return result;

    }

    /**
     * 资金类型列表
     *
     * @see <a href="https://huoyan.kaolakuaishou.cn/project/97/interface/api/14621">火眼地址</a>
     */
    @ExcludeInterceptor
    @PostMapping("/account/yxy/fund/type")
    public Result accountYxyFundType(@RequestBody ManageFundTypeListDTO dto) {

        List<JSONObject> fundTypeList = new ArrayList<>();

        if (Objects.nonNull(dto.getChangeFundFlag())
                && ManageChangeFundDTO.REVERSAL_AMOUNT.equals(dto.getChangeFundFlag())) {

            if (AccountType.MER.isEqualsFullAccountNo(dto.getAccountType())
                    || AccountType.MERCHANT_FROM_BOSS.isEqualsFullAccountNo(dto.getAccountType())) {
                JSONObject fundType = new JSONObject();
                fundType.put("name", AccountMainJournalType.MERCHANT_REFUND.getName());
                fundType.put("value", AccountMainJournalType.MERCHANT_REFUND.getCode());
                fundTypeList.add(fundType);
                return Result.builder().success(fundTypeList);
            }

            if (AccountType.ALLY_V2.isEqualsFullAccountNo(dto.getAccountType())
                    || AccountType.ALLY_FROM_BOSS.isEqualsFullAccountNo(dto.getAccountType())) {
                JSONObject fundType = new JSONObject();
                fundType.put("name", AccountMainJournalType.ALLY_REFUND.getName());
                fundType.put("value", AccountMainJournalType.ALLY_REFUND.getCode());
                fundTypeList.add(fundType);
                return Result.builder().success(fundTypeList);
            }

        } else {

            if (AccountType.MER.isEqualsFullAccountNo(dto.getAccountType())
                    || AccountType.MERCHANT_FROM_BOSS.isEqualsFullAccountNo(dto.getAccountType())) {
                JSONObject fundType = new JSONObject();
                fundType.put("name", AccountMainJournalType.MERCHANT.getName());
                fundType.put("value", AccountMainJournalType.MERCHANT.getCode());
                fundTypeList.add(fundType);
                return Result.builder().success(fundTypeList);
            }

            List<AccountMainJournalType> allyJournalType = Arrays.asList(
                    AccountMainJournalType.ALLY_ACTIVATE, AccountMainJournalType.ALLY_REACH,
                    AccountMainJournalType.ALLY_PROFIT, AccountMainJournalType.ALLY_ACTIVITY);
            for (AccountMainJournalType value : allyJournalType) {
                JSONObject fundType = new JSONObject();
                fundType.put("name", value.getName());
                fundType.put("value", value.getCode());
                fundTypeList.add(fundType);
            }
        }
        return Result.builder().success(fundTypeList);
    }


    /**
     * 列出用户的账单类型
     *
     * @see <a href="https://huoyan.kaolakuaishou.cn/project/97/interface/api/14806">火眼接口连接</a>
     */
    @ExcludeInterceptor
    @PostMapping("/ally/fund/bill/type")
    public Result allyFundBillType(@Validated @RequestBody ManageRemoveWithdrawalDebitListDTO dto, BindingResult br) {
        List<JSONObject> billTypeList = tradeService.allyFundBillType();
        JSONObject fundBillJson = new JSONObject();
        fundBillJson.put("name", FundBillType.TYPE_460.getName());
        fundBillJson.put("type", FundBillType.TYPE_460.getType());
        billTypeList.add(fundBillJson);
        return Result.builder().success(billTypeList);
    }

}
